package com.lining.orangeservice.service;


import cn.hutool.captcha.LineCaptcha;
import cn.hutool.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

/**
 * 验证码服务
 */
@Service
public class CaptchaService {

    private static final int WIDTH = 120;
    private static final int HEIGHT = 40;
    private static final int LENGTH = 4;

    /**
     * 生成图形验证码
     * @return 验证码信息
     */
    public JSONObject generateCaptcha() {
        // 创建验证码对象
        LineCaptcha captcha = new LineCaptcha(WIDTH, HEIGHT);
        
        // 获取验证码文本
        String code = captcha.getCode();
        
        // 转换为Base64编码的图片数据
        BufferedImage image = captcha.getImage();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", outputStream);
        } catch (IOException e) {
            throw new RuntimeException("验证码生成失败", e);
        }
        
        String base64Image = Base64.getEncoder().encodeToString(outputStream.toByteArray());
        
        // 返回验证码信息
        JSONObject result = new JSONObject();
        result.put("code", code);
        result.put("image", base64Image);
        
        return result;
    }

    /**
     * 验证验证码是否正确
     * @param code 用户输入的验证码
     * @param sessionCode 会话中存储的验证码
     * @return 是否正确
     */
    public boolean validateCaptcha(String code, String sessionCode) {
        if (sessionCode == null || code == null) {
            return false;
        }
        return sessionCode.equalsIgnoreCase(code);
    }
}